const { BaseCommand } = require("./base");
const _path = require("node:path");
const {
    get_file_list,
    get_fst_file,
    get_full_path,
    processRename,
} = require("../utils/file_tool");
const _fs = require("node:fs");
const { progress } = require("../utils/display_tool");
const { Alignment, alignStr } = require("../utils/transform_tool");
const { clearLine } = require("../utils/interaction_tool");
const { info } = require("../utils/log_tool");

class ZipDataCommand extends BaseCommand {
    async execute() {
        const AdmZip = require("adm-zip");
        const data = this.selfData;
        /** @type { {path: string, content: string | Buffer}[] } */
        const entries = this.selfData.entries;
        // creating archives
        var zip = new AdmZip();

        for (let index = 0; index < entries.length; index++) {
            const entry = entries[index];
            let entryName = entry.path;
            entryName = processRename(entryName, data.options?.rename);
            const show_src = entryName;
            progress(index, entries.length, {
                desc: `Add ${show_src}`,
                depth: 0,
                align: true,
            });
            // zip.addLocalFile(file, zipPath);
            zip.addFile(entryName, entry.content);
        }
        clearLine();
        progress(entries.length, entries.length, {
            desc: `压缩中...`,
            depth: 0,
            align: true,
        });
        // or write everything to disk
        if (data.dst) {
            const dst = get_full_path(data.dst);
            await new Promise((resolve) => {
                zip.writeZip(dst, (err) => {
                    if (err) {
                        throw err;
                    }
                    resolve();
                });
            });
        } else {
            const buffer = zip.toBuffer();
            return buffer;
        }
        progress(entries.length, entries.length, {
            desc: `压缩完成!`,
            depth: 0,
            color: "green",
        });
        info("");
    }
}

module.exports = {
    ZipDataCommand,
};
